<?php

class Skjb_Office_Spreadsheet_Exporter_Csv
{
    private $_spreadsheet = null;
    
    public function __construct(Skjb_Office_Spreadsheet $spreadsheet)
    {
        $this->_spreadsheet = $spreadsheet;
    }
    
    public function getRawExport()
    {
        if (count($this->_spreadsheet->sheets) > 1) {
            throw new Exception('CSV format only allows one sheet');
        }
        
        $output = '';
        
        $sheet = $this->_spreadsheet->sheets[0];
        
        foreach ($sheet->rows as $row) {
            if (count($row->cells) > 0) {
                $first = true;
                foreach ($row->cells as $cell) {
                    if (!$first) {
                        $output .= ',';
                    }
                    $value = $cell->getDisplayValue();
                    if (strpos($value, ',') !== false || $value == 'ID') {
                        $output .= '"' . str_replace('"', '""', $value) . '"';
                    } else {
                        $output .= $value;
                    }
                    $first = false;
                }
            }
            $output .= "\r\n";
        }
        
        return $output;
    }
}
